package com.alogic.xscript.plugins;

import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;

import java.io.Console;


/**
 * 标准输出
 *
 * @since 1.6.14.3 [20210322 duanyy] <br>
 */
public class Stdout extends AbstractLogiclet {
    protected String $msg;
    protected boolean newline = true;

    public Stdout(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);

        $msg = PropertiesConstants.getRaw(p,"msg",$msg);
        newline = PropertiesConstants.getBoolean(p,"newline",newline,true);
    }

    @Override
    protected void onExecute(XsObject root, XsObject current, LogicletContext ctx, ExecuteWatcher watcher) {
        String msg = PropertiesConstants.transform(ctx,$msg,"");
        if (StringUtils.isNotEmpty(msg)){
            Console console = System.console();
            if (console == null) {
                if (newline){
                    System.out.println(msg);
                }else {
                    System.out.print(msg);
                }
            }else{
                if (newline) {
                    console.printf(msg);
                }else{
                    console.printf("%s\n",msg);
                }
            }
        }
    }
}